package com.wugh.fast.demo.config.bean;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 说明: 自动处理 feign请求时的授权信息
 *
 * @author wugh
 * @date 2019-04-30 18:03
 */
@Component
@Slf4j
public class FeignSecurityAuthRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            log.debug("无法获取当前的Request信息");
            return;
        }
        String token = StringUtils.defaultString(request.getHeader("Authorization"), request.getParameter("AUTH2_TOKEN_PARAMETER_NAME"));
        if (StringUtils.isNotBlank(token)) {
            template.header("Authorization", StringUtils.startsWithIgnoreCase(token, "Bearer ") ? token : ("Bearer " + token));
        }
        String simpleToken = request.getHeader("FEIGN_SIMPLE_AUTH2_HEADER_NAME");
        if (StringUtils.isNotBlank(simpleToken)) {
            template.header("FEIGN_SIMPLE_AUTH2_HEADER_NAME", simpleToken);
        }
    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes != null ? requestAttributes.getRequest() : null;
    }
}
